<template>
  <div>
     <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 背景卡片 -->
  <el-card class="box-card">
    <el-alert
    title="注意：只允许选择第三级分类设置相关参数！"
    type="warning"
    show-icon>
  </el-alert>
  <el-row class="row-opt">
    <el-col>
      <span>选择商品分类：</span>
      <!-- 级联选择框区域 -->
       <el-cascader
       expand-trigger="hover"
       :options="catelist"
       :props="cascaderProps"
       v-model="selectedKeys"
       @change="handlerChanged"
       clearable>
      </el-cascader>
    </el-col>
  </el-row>
  <!-- tab标签页区域 -->
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="动态参数" name="many">
      <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="openAddDialog">添加参数</el-button>
      <!-- 动态参数表格 -->
     <el-table :data="manyTable" border stripe>
       <el-table-column type="expand">
         <template slot-scope="scope">
            <el-tag closable @close="handleClose(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>

         </template>
       </el-table-column>
       <el-table-column type="index" label="#"></el-table-column>
       <el-table-column label="分类名称" prop="attr_name"></el-table-column>
       <el-table-column label="操作">
         <template slot-scope="scope">
           <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditParams(scope.row)">编辑</el-button>
           <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
         </template>
       </el-table-column>
     </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
      <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="openAddDialog">添加属性</el-button>
      <!-- 静态属性表格 -->
      <el-table :data="onlyTable" border stripe>
       <el-table-column type="expand">
         <template slot-scope="scope">
            <el-tag closable @close="handleClose(i,scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>

         </template>
       </el-table-column>
       <el-table-column type="index" label="#"></el-table-column>
       <el-table-column label="属性名称" prop="attr_name"></el-table-column>
       <el-table-column label="操作">
          <template slot-scope="scope">
           <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditParams(scope.row)">编辑</el-button>
           <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
         </template>
       </el-table-column>
     </el-table>
    </el-tab-pane>
  </el-tabs>
  <!-- dialog区域，添加参数/添加属性 -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogColsed"
      >
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
          <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
              </el-form-item>
          </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addParams">确 定</el-button>
    </span>
    </el-dialog>
    <!-- dialog区域，编辑参数/添加属性 -->
    <el-dialog
      :title="activeName == 'many' ? '编辑动态参数' : '编辑静态属性'"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogColsed"
      >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
          <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
              <el-input v-model="editForm.attr_name"></el-input>
              </el-form-item>
          </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editParams">确 定</el-button>
    </span>
    </el-dialog>
  </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
       // 父级分类列表
      catelist: [],
      // 指定级联选择器的配置对象
      // value,指定选项的值为选项对象的某个属性值
      // label,指定选项标签为选项对象的某个属性值
      // children,指定选项的子选项为选项对象的某个属性值
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中的父级分类的ID数组
      selectedKeys: [],
      // tab标签页选中的标签
      activeName: 'many',
      // 动态参数和静态属性的数据
      manyTable: [],
      onlyTable: [],
      // 添加参数/添加属性的对话框显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单对象
      addForm: {
        attr_name: ''
      },
      // 添加参数的表单的验证规则
      addFormRules: {
         attr_name: [{ required: true, message: '请输入参数或属性名称', trigger: 'blur' }]
      },
      // 编辑参数/添加属性的对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑参数的表单对象
      editForm: {
      },
      // 编辑参数的表单的验证规则
      editFormRules: {
         attr_name: [{ required: true, message: '请输入参数或属性名称', trigger: 'blur' }]
      }
    }
    },
    computed: {
      // 如果级联选择框选中的不是三级分类，按钮则处于禁用状态
      isBtnDisabled() {
        if (this.selectedKeys.length !== 3) { return true }
         return false
      },
      // 选中的第三级分类的ID
      cateId() {
        if (this.selectedKeys.length === 3) {
          return this.selectedKeys[2]
        }
        return null
      }
    },
    created() {
     this.getCateList()
    },
    methods: {
     // 查询商品分类集合
      async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类列表失败！')
      this.catelist = res.data
      // console.log(this.catelist)
     },
    //  监听级联选择框的变化
      handlerChanged() {
      // console.log(this.selectedKeys)
      // 只能选三级分类设置参数，通过判断selectedKeys选择的数组长度判定选择是否为三级分类
       this.getParamsList()
    },
    // 标签页点击事件
    handleClick() {
      this.getParamsList()
    },
    // 获取tab页签的相关数据
    async getParamsList() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTable = []
        this.onlyTable = []
        return
      }
      // console.log(this.cateId)

      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
       { params: { sel: this.activeName } })
      //  console.log(res)

       if (res.meta.status !== 200) {
         return this.$message.error('获取属性参数失败！')
       }

        // 将attr_vals字符串转换成数组，方便后期映射到tag标签
       res.data.forEach(item => {
         item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
         item.inputVisible = false
         item.inputValue = ''
      })

      //  获取到的属性，通过判断分给两个不同的页签
      if (this.activeName === 'many') {
        this.manyTable = res.data
      } else {
        this.onlyTable = res.data
      }
    },
    // 点击打开添加动态参数/静态属性的对话框
    openAddDialog() {
      this.addDialogVisible = true
    },
    // 动态参数/静态属性的对话框关闭
    addDialogColsed() {
      // 清空
      this.$refs.addFormRef.resetFields()
    },
    // 添加动态参数/静态属性
      addParams() {
        this.$refs.addFormRef.validate(async valid => {
          // 验证不通过直接return
          if (!valid) return
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName })
              console.log(res)
              if (res.meta.status !== 201) {
                return this.$message.error('添加参数失败！')
              }
              this.$message.success('添加参数成功！')
              this.addDialogVisible = false
              this.getParamsList()
        })
      },

      // 点击编辑按钮，打开编辑对话框
      openEditParams(row) {
        this.editDialogVisible = true
        // 并将点击的对象复制给editform，并拿到编辑对话框中用来编辑
        // console.log(row)

        this.editForm = row
      },
      // 监听编辑对话关闭
      editDialogColsed() {
        this.$refs.editFormRef.resetFields()
        this.getParamsList()
      },
      // 点击事件，编辑参数
      editParams() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                                  { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
          console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error('编辑参数失败！')
          }
          this.$message.success('修改参数成功！')
          this.editDialogVisible = false
          // this.getParamsList()
       })
      },
      // 点击事件，删除参数
      async removeParams(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 用户取消了删除的操作
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除！')
        }

        // 删除的业务逻辑
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${id}`
        )

        if (res.meta.status !== 200) {
          return this.$message.error('删除参数失败！')
        }
        this.$message.success('删除参数成功！')
        this.getParamsList()
       },
      //  点击标签，打开输入框
       showInput(scope) {
         scope.row.inputVisible = true
        //  让文本框自动获得焦点
        // $nextTick方法的作用，当页面上的元素被重新渲染之后，才能执行回调函数
         this.$nextTick(_ => {
         this.$refs.saveTagInput.$refs.input.focus()
        })
       },
      // 添加标签，失去焦点，按下回车都可以触发
       async handleInputConfirm(row) {
         if (row.inputValue.trim().length === 0) {
           row.inputValue = ''
           row.inputVisible = false
           return
         }
         row.attr_vals.push(row.inputValue.trim())
         row.inputValue = ''
         row.inputVisible = false
         this.saveAttrVals(row)
       },
      //  删除参数标签
       handleClose(i, row) {
        //  通过splice删除数组，因为splice会修改原数组，所以将数组保存到数据库
         row.attr_vals.splice(i, 1)
         this.saveAttrVals(row)
       },
      //  对attr_vals的操作，保存到数据库
      async saveAttrVals(row) {
         const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
           attr_name: row.attr_name,
           attr_sel: row.attr_sel,
           attr_vals: row.attr_vals.join(' ')
         })
         if (res.meta.status !== 200) {
           this.$message.error('修改参数项失败')
         }
         this.$message.success('修改参数成功')
      }
    }

}

</script>

<style lang="less" scoped>
.row-opt {
  margin: 15px 0;
}
.el-tag{
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
